package cn.sofwin.blog.servlet;

import cn.sofwin.blog.entity.User;
import cn.sofwin.blog.service.UserService;
import cn.sofwin.blog.service.impl.UserServiceImpl;
import cn.sofwin.blog.utils.HttpHelper;
import org.apache.commons.lang3.StringUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 控制器
 * @author LetCode
 * @since 1.0
 *
 */
@WebServlet("/user/register")
public class RegisterServlet extends HttpServlet {

    private UserService userService = UserServiceImpl.getInstance();

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.getRequestDispatcher("/register.jsp").forward(req,resp);

    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //处理注册请求
        HttpHelper.charset(req);

        String username=req.getParameter("username");
        String password=req.getParameter("password");
        String nickname=req.getParameter("nickname");
        if (StringUtils.isBlank(username)|| StringUtils.isBlank(password)){
            HttpHelper.error("用户名或密码错误",req,resp);
        }else{
            User user=userService.register(username,password,nickname);
            if (user==null){
                HttpHelper.error("用户名已存在",req,resp);
            }else {
                //重定向到登录页面
                resp.sendRedirect("/user/login");
            }
        }
    }


}